package com.longteng.lesson2.controller;

import com.longteng.lesson2.util.TelnetSocket;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/dubbo")
public class DubboController {
    @RequestMapping("/dubboPage")
    public ModelAndView dubboPage(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("dubbo");
        modelAndView.addObject("address","47.105.55.243:2181");
        return modelAndView;
    }
    @RequestMapping("/invoke")
    public @ResponseBody
    String invoke(String param,String methodName,String interfaceName,String ip,String encoding){
        String[] ips =ip.split(":");
        try {
            TelnetSocket telnetSocket=new TelnetSocket(ips[0],Integer.parseInt(ips[1]));
            telnetSocket.setReadEncoding(encoding);
            String ls=telnetSocket.send("invoke  "+interfaceName+"."+methodName+"("+param+")");
            ls=ls.replace("dubbo>","");
            return ls;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/resolveMethod")
    public
    @ResponseBody
    List<String> resolveMethod(String ip,String interfaceName){
        String[] ips =ip.split(":");
        List<String> methods=new ArrayList<>();
        try {
            TelnetSocket telnetSocket=new TelnetSocket(ips[0],Integer.parseInt(ips[1]));
            String ls=telnetSocket.send("ls  "+interfaceName);
            ls=ls.replace("dubbo>","");
            String[] methodArray =ls.split("\r\n");
            methods=Arrays.asList(methodArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return methods;
    }
    @RequestMapping("/resolveIp")
    public @ResponseBody
    List<String> resolveIp(String address, String interfaceName){
        ZkClient zkClient=new ZkClient(address);
        List<String>
                dubboNodeList=zkClient.getChildren("/dubbo/"+interfaceName+"/providers");
        List list=new ArrayList();
        for(String s:dubboNodeList){
            try {
                String url = URLDecoder.decode(s, "UTF-8");
                String ip  =url.substring(url.indexOf("//")+2,url.lastIndexOf("/"));
                //因为阿里云服务器虚拟ip的问题，返回的实际服务器ip，172开头的，在外网是无法访问的，
                //这里简单替换成对外的虚拟ip 47.105.55.243
                ip=ip.replace("172.31.145.55","47.105.55.243");
                list.add(ip);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return list;
    }
}
